﻿//*************************************************************************************
//* 作    者： 
//* 创建时间： 2021-12-15 12:42:49
//* 描    述： 

//* ************************************************************************************
using System;
using System.Collections.Generic;
using UnityEngine;

public class AsyncResourceAudioClipLoader : UFrame.Audio.IAudioClipLoader
{
    private Dictionary<string, AudioClip> m_loadedClips = new Dictionary<string, AudioClip>();
    private Dictionary<string, Action<AudioClip>> m_asyncEvents = new Dictionary<string, Action<AudioClip>>();
    public void ClearAllLoaded()
    {
        m_loadedClips.Clear();
    }

    public void FindClip(string id, bool isSfx, Action<AudioClip> onLoad)
    {
        if (m_loadedClips.TryGetValue(id, out var clip) && clip)
        {
            onLoad?.Invoke(clip);
            return;
        }

        var request = Resources.LoadAsync<AudioClip>(id);
        request.completed += (operation) =>
        {
            if (request.asset)
                onLoad?.Invoke(request.asset as AudioClip);
            else
                Debug.LogError("failed load audio clip:" + id);
        };
    }

    public void FindClip(int id, bool isSfx, Action<AudioClip> onLoad)
    {
        var audioCfg = TableAgent.Instance.GetSoundCfgById(id);
        if (audioCfg != null)
        {
            FindClip(audioCfg.path, isSfx, onLoad);
        }
    }
}
